package net.misp.beta.notepad;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements TextWatcher {

	TextView lblTitle;
	EditText edtMain, edtSearch;
	String mString;
	int mSelect = 0;
	boolean isDirty = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		lblTitle = (TextView) findViewById(R.id.lbl_title);
		edtMain = (EditText) findViewById(R.id.edt_main);
		edtSearch = (EditText) findViewById(R.id.edt_search);
		edtMain.addTextChangedListener(this);
		edtSearch.addTextChangedListener(this);
		mString = new String();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_save:
			save();
			isDirty = false;
			break;
		case R.id.menu_exit:
			saveChk();
			break;
		case R.id.menu_settings:
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);

			break;
		case R.id.menu_undo:

			break;

		default:
			break;
		}
		return true;
	}

	private void saveChk() {
		if (isDirty) {
			new AlertDialog.Builder(this)
					.setTitle(R.string.dlg_title_alert)
					.setMessage(R.string.dlg_message_exit)
					.setPositiveButton(R.string.yes, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							finish();
						}
					})
					.setNeutralButton(R.string.save_finish,
							new OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									save();
									finish();
								}
							}).setNegativeButton(R.string.no, null).show();
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("title", lblTitle.getText().toString());
		outState.putString("value", edtMain.getText().toString());
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		lblTitle.setText(savedInstanceState.getString("title"));
		edtMain.setText(savedInstanceState.getString("value"));
		mString = edtMain.getText().toString();
		super.onRestoreInstanceState(savedInstanceState);
	}

	public void onSearch(View view) {
		mString = edtMain.getText().toString();
		String search = edtSearch.getText().toString();
		mSelect = mString.indexOf(search, mSelect);
		if (mSelect == -1) {
			Toast.makeText(this, "String was not found.", Toast.LENGTH_SHORT)
					.show();
			mSelect = 0;
		} else {
			edtMain.setSelection(mSelect, mSelect
					+ edtSearch.getText().toString().length());
			edtMain.requestFocus();
			mSelect = mSelect + edtSearch.getText().toString().length();
		}
	}

	@Override
	public void afterTextChanged(Editable editable) {
		// TODO 自動生成されたメソッド・スタブ

	}

	@Override
	public void beforeTextChanged(CharSequence charsequence, int i, int j, int k) {
		// TODO 自動生成されたメソッド・スタブ

	}

	@Override
	public void onTextChanged(CharSequence charsequence, int i, int j, int k) {
		mSelect = 0;
		mString = edtMain.getText().toString();
		isDirty = true;
	}

	public void save() {
		mString = edtMain.getText().toString();

		File dir = new File(Environment.getExternalStorageDirectory(),
				getPackageName());

		if (!dir.exists()) {
			dir.mkdirs();
		}

		File file = new File(dir, getFileName());

		String message;

		try {
			FileOutputStream outStream = new FileOutputStream(file);
			OutputStreamWriter writer = new OutputStreamWriter(outStream);
			writer.write(mString);
			writer.flush();
			writer.close();

			message = "File saved.";
		} catch (FileNotFoundException e) {
			message = e.getMessage();
			e.printStackTrace();
		} catch (IOException e) {
			message = e.getMessage();
			e.printStackTrace();
		}

		Toast.makeText(this, message, Toast.LENGTH_LONG).show();

		isDirty = false;
	}

	private String getFileName() {
		Calendar cal = Calendar.getInstance(Locale.JAPAN);
		return String.valueOf(cal.getTimeInMillis()) + ".txt";
	}
}
